﻿using MySql.Data.MySqlClient;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectShare
{
    public class ConnectFactory
    {
        public ConnectFactory(DapperCRUD.Dialect dbtype)
        {
            _dbtype = dbtype;
        }
        private static DapperCRUD.Dialect _dbtype;
        public static IDbConnection GetOpenConnection()
        {
            IDbConnection connection;
            if (_dbtype == DapperCRUD.Dialect.PostgreSQL)
            {
                connection = new NpgsqlConnection(GetConnectionStr());
                DapperCRUD.SetDialect(DapperCRUD.Dialect.PostgreSQL);
            }
            else if (_dbtype == DapperCRUD.Dialect.SQLite)
            {
                //connection = new SQLiteConnection(GetConnectionStr());
                connection = new SqlConnection(GetConnectionStr());
                DapperCRUD.SetDialect(DapperCRUD.Dialect.SQLite);
            }
            else if (_dbtype == DapperCRUD.Dialect.MySQL)
            {
                connection = new MySqlConnection(GetConnectionStr());
                DapperCRUD.SetDialect(DapperCRUD.Dialect.MySQL);
            }
            else
            {
                connection = new SqlConnection(GetConnectionStr());
                DapperCRUD.SetDialect(DapperCRUD.Dialect.SQLServer);
            }
            connection.Open();
            return connection;
        }
        public static string GetConnectionStr(string defaultValue = "")
        {
            string result;
            try
            {
                result = CustomFun.GetConfigAppSetting("DBConnectionString");
            }
            catch
            {
                result = defaultValue;
            }
            return result;
        }
    }
}
